import pandas as pd
from sklearn.preprocessing import LabelEncoder,MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import matplotlib.pyplot as pyplot
import numpy as np
import math


# 给定输入、输出序列的长度，它可以自动地将时间序列数据转型为适用于监督学习的数据
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    # n_vars为列数
    n_vars = 1 if type(data) is list else data.shape[1]
    df = pd.DataFrame(data)
    cols, names = list(), list()
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
    # put it all together
    agg = pd.concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    # 它的返回值只有一个, 即转型后适用于监督学习的DataFrame
    return agg





dataset1 = pd.read_csv('/mnt/715/temp/feature_08.csv', header=0)

dataset2 = pd.read_csv('/mnt/715/temp/feature_0901.csv', header=0)

values1 = dataset1.values

values2=dataset2.values

values=np.concatenate((values1,values2),axis=0)
# LabelEncoder是对不连续的数字或文本编号。
#encoder = LabelEncoder()
#values[:, 4] = encoder.fit_transform(values[:, 4])

# ensure all data is float
values = values.astype('float32')
# 数据归一化
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# 将数据规整成为可以放进神经网络的dataframe。
reframed = series_to_supervised(scaled, 1, 1)
# drop columns we don't want to predict
reframed.drop(reframed.columns[57:112], axis=1, inplace=True)
#reframed.drop(reframed.columns[40], axis=1, inplace=True)
#reframed.to_csv('aaa.csv')

print(reframed.head())



values = reframed.values
#n_train = int(len(values)*0.4)
n_train=dataset1.shape[0]-3
train = values[:n_train, :]
test = values[n_train:, :]
# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)


# design network
model = Sequential()
# 50为units，是指每个cell中隐藏层结构的参数数量，即经过一个cell之后，数据的维度变为50。
# 假如我们输入有100个句子，每个句子都由5个单词组成，而每个单词用64维的词向量表示。
# 那么samples=100，timesteps=5，input_dim=64，
# 可以简单地理解timesteps就是输入序列的长度。
# input_shape：输入形状
# model.add(Bidirectional(LSTM(50, return_sequences=True),
#                         input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X,train_y,epochs=100,batch_size=72,validation_data=(test_X, test_y),
                    verbose=2,shuffle=False)
model.save('air_analysis.model')
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
# 显示图例：
#pyplot.legend()
#pyplot.show()


# make a prediction
# 1、测试集是处理之后的数据：新的数据在输入模型之前需要进行一系列同上的操作，
# 所以需要实现数据的预处理模型，将其整理为一个对应的方法。
# 2、将整理好的数据放入模型中处理：
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
print(test_X)
# invert scaling for forecast concatenate：数据拼接
inv_yhat = np.concatenate((yhat, test_X[:, 1:]), axis=1)
print(inv_yhat)
# 3、是将标准化后的数据转换为原始数据：
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
inv_y = scaler.inverse_transform(test_X)
inv_y = inv_y[:,0]

# calculate RMSE:均方根误差
#rmse = math.sqrt(mean_squared_error(inv_y, inv_yhat))
#print('Test RMSE: %.3f' % rmse)

#输出预测的ata
print(inv_yhat)








